﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;

namespace Wicresoft.UnifyShow.Portal
{
    public class BaseController : Controller
    {
        private string _cookieKey;
        //in order to SSO,this site must be one of the sub-domain like:
        //unify.fjyc.com
        //the parent domain or other sub-domain site will set cookie for the parent domain,
        //and try to get cookie(UNI_SESS).
        //if cookie exist,indicate user is authenticated.
        //otherwise return to own login page
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            if(_cookieKey == null)
            {
                //get cookie key
                _cookieKey = System.Configuration.ConfigurationManager.AppSettings["SSOCookie"];
            }

            //not set SSOCookie config,don't try SSO Authentication
            if(string.IsNullOrEmpty(_cookieKey)) return;

            //try get cookie
            var cookie = requestContext.HttpContext.Request.Cookies[_cookieKey];
            //SSO cookie exsit
            if (cookie != null)
            {
                //has SSO
                CreateUserBySSO(cookie);
            }
            else
            {
                string user = CustomLoginUtil.GetUser();
                if (string.IsNullOrEmpty(user)) return;
                User2 = new CustomPrincipal(
                    user,//cn
                    string.Empty,//uid
                    string.Empty,//dept
                    null,//logintime
                    ".local"
                );
            }

            
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (User2 != null && User2.Identity != null && User2.Identity.IsAuthenticated)
                return;
            filterContext.Result = new HttpUnauthorizedResult();
        }

        private void CreateUserBySSO(HttpCookie sCookie)
        {
            string[] splits = DecryptSSOCookie(sCookie.Value).Split('&');

            User2 = new CustomPrincipal(
                splits[0],//cn
                splits[1],//uid
                splits[2],//dept
                DateTime.Parse(splits[4]),//logintime
                "SSO"
            );
        }

        private string DecryptSSOCookie(string org)
        {
            //TODO, mock now, wait for decrypt method
            return string.Empty;
 
        }

        public IPrincipal User2 { get; private set; }

    }
}